const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class MyPromise {
  constructor(executor) {
    //promise状态
    this.status = PENDING;
    //成功之后的值
    this.value = undefined;
    //失败之后的原因
    this.reason = undefined;
    //成功回调
    this.successCallback = [];
    //失败回调
    this.failCallback = [];
    let resolve = (value) => {
      //如果状态不是PENDING 停止执行
      if (this.status !== PENDING) return;
      //将状态改为FULFILLED
      this.status = FULFILLED;
      //保存成功后的值
      this.value = value;
      //执行成功回调
      this.successCallback.forEach((fn) => fn());
    };
    let reject = (reason) => {
      //如果状态不是REJECTED 停止执行
      if (this.status !== PENDING) return;
      //将状态改为REJECTED
      this.status = REJECTED;
      //保存成功后的值
      this.reason = reason;
      //执行成功回调
      this.failCallback.forEach((fn) => fn());
    };
    try {
      executor(resolve, reject);
    } catch (e) {
      reject(e);
    }
  }
  then(successCallback, failCallback) {
    //如果不传回调
    successCallback = successCallback ? successCallback : (value) => value;
    failCallback = failCallback
      ? failCallback
      : (reason) => {
          throw reason;
        };
    let promise2 = new MyPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);
            reslovePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);
            reslovePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      } else {
        //等待PENDING状态
        //将成功状态个失败状态存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              reslovePromise(promise2, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          }, 0);
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              reslovePromise(promise2, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          }, 0);
        });
      }
    });
    return promise2;
  }
  static all(arr) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData(i, value) {
        result[i] = value;
        index++;
        if (arr.length === index) {
          resolve(result);
        }
      }
      for (let i = 0; i < arr.length; i++) {
        let current = arr[i];
        if (current instanceof MyPromise) {
          current.then(
            (value) => addData(i, value),
            (reason) => reject(reason)
          );
        } else {
          addData(i, current);
        }
      }
    });
  }
  static race(arr) {
    return new MyPromise((resolve, reject) => {
      for (let i = 0; i < arr.length; i++) {
        let current = arr[i];
        if (current instanceof MyPromise) {
          current.then(
            //直接执行，状态不可修改
            (value) => resolve(value),
            (reason) => reject(reason)
          );
        } else {
          resolve(current);
        }
      }
    });
  }
  static resolve(value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise((resolve) => resolve(value));
  }
  finally(callback) {
    //finally返回的是一个promise将上一级的resolve传到下一个then同时执行callback
    return this.then(
      (value) => {
        return MyPromise.resolve(callback()).then(() => value);
      },
      (reason) => {
        return MyPromise.resolve(callback()).then(() => {
          throw reason;
        });
      }
    );
  }
  catch(failCallback) {
    //catch 只接受reject
    return this.then(undefined, failCallback);
  }
}
function reslovePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError("Chaining cycle detected for promise"));
  }
  if (x instanceof MyPromise) {
    //then中返回的是一个promise
    x.then(
      (value) => resolve(value),
      (reason) => reject(reason)
    );
  } else {
    //普通值
    resolve(x);
  }
}
module.exports = MyPromise;
